package com.fingard.dsp.bank.directbank.ceb01;


import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.Date;
import java.util.UUID;
@Component("CEB01SinglePay")
public class CEB01SinglePay extends CEB01Base implements ISinglePay {

    private static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";


    /**
     * 单笔支付指令提交
     * @param p_req1908
     * @return
     * @throws Exception
     */
    //，不需采用流处理方式
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail;
        tmpRetDetail = d_190802(p_req1908);
        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    //190802对外支付
    private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        CEB01Header bankHeader = new CEB01Header();
        bankHeader.TransCode = "b2e004001";
        bankHeader.batchID = p_req1908.singleDetail.askNumber;
        bankHeader.JnlDateTime = p_req1908.singleDetail.getPayDateTime();
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        writeCommonHeader_2(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("TransContent");
        XElement tmpXElement = new XElement("ReqData", "");
        tmpXElement.addChild(new XElement("ClientPatchID", p_req1908.singleDetail.askNumber));
        if (p_req1908.singleDetail.sameBnk.equals("1")) {
            tmpXElement.addChild(new XElement("transferType", "2122"));
        } else {
            tmpXElement.addChild(new XElement("transferType", "2120"));
        }
        tmpXElement.addChild(new XElement("accountNo", p_req1908.singleDetail.payAct));
        tmpXElement.addChild(new XElement("toAccountName", p_req1908.singleDetail.recName));
        tmpXElement.addChild(new XElement("toAccountNo", p_req1908.singleDetail.recAct));
        tmpXElement.addChild(new XElement("toBank", p_req1908.singleDetail.getOppBankLocation()));
        tmpXElement.addChild(new XElement("amount", p_req1908.singleDetail.payAmount));
        tmpXElement.addChild(new XElement("toLocation", ""));
        tmpXElement.addChild(new XElement("clientSignature", ""));
        tmpXElement.addChild(new XElement("checkNo", ""));
        tmpXElement.addChild(new XElement("checkPassword", ""));
        tmpXElement.addChild(new XElement("noteOther", p_req1908.singleDetail.description));
        tmpXElement.addChild(new XElement("bankNo", p_req1908.singleDetail.cnapsCode));
        //isUrgent
        //0，不加急     1，加急		注：转账类型为2124―跨行互联转账时，只能上送0
        if (p_req1908.singleDetail.paySpd.equals("1")) {
            tmpXElement.addChild(new XElement("isUrgent", "1"));
        } else {
            tmpXElement.addChild(new XElement("isUrgent", "0"));
        }
        tmpXElement.addChild(new XElement("cellphone", ""));
        //perOrEnt 收款账户对公对私标志 0对公 1对私
        if (p_req1908.singleDetail.isPrivate.equals("1")) {
            tmpXElement.addChild(new XElement("perOrEnt", "1"));
            String note = "";
            boolean enableNoteFrom = getBankConfig().getValueAsBool("enableNoteFrom");
            if (enableNoteFrom) {
                String noteFrom = getBankConfig().getValueAsString("noteFrom");
                if (StringHelper.hasAnyChar(noteFrom)) {
                    note = getBankConfig().getMapValueByKey("useMapping", p_req1908.singleDetail.srcXElement.getSingleText(noteFrom));
                    if (StringHelper.isNullOrEmpty(note)) {
                        note = p_req1908.singleDetail.srcXElement.getSingleText(noteFrom);
                    }
                }
            } else {
                note = getBankConfig().getMapValueByKey("useMapping", p_req1908.singleDetail.purpose);
                if (StringHelper.isNullOrEmpty(note)) {
                    note = getBankConfig().getMapValueByKey("useMapping", p_req1908.singleDetail.payType);
                }
            }
            tmpXElement.addChild(new XElement("note", note));
        } else {
            tmpXElement.addChild(new XElement("perOrEnt", "0"));
            if (StringHelper.isNullOrEmpty(p_req1908.singleDetail.purpose)) {
                tmpXElement.addChild(new XElement("note", p_req1908.singleDetail.abstractATS));
            } else {
                tmpXElement.addChild(new XElement("note", p_req1908.singleDetail.purpose));
            }
        }
        Connection conn = FGBiz.getLocalDbConn();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //将ATS对账码与银行返回业务流水号建立映射，在查询流水时通过查询流水接口返回的业务流水号查回对账码返回ATS
        JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_req1908.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req1908.singleDetail.askNumber, p_req1908.singleDetail.abstractATS});

        tmpXElement.addChild(new XElement("IsAudit", "0"));
        //matchRule 注：转账类型为2124时必须为空
        tmpXElement.addChild(new XElement("matchRule", "1"));
        tmpXElement.addChild(new XElement("innerCheckAccNo", p_req1908.singleDetail.askNumber));
        nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
        xmlWriter.writeXElement(tmpXElement);
        xmlWriter.writeEndDocument();//写入报文完成
        String[] tmpStrRet = sendToBank_2(xmlWriter.toXmlString(), bankHeader.TransCode);//发送银行
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            //解析银行返回
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String tmpReturnCode = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnCode");
                String tmpReturnMsg = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnMsg");
                String tmperror = "";
                if (tmpReturnCode == null && tmpReturnMsg == null) {
                    tmpReturnCode = tmpBkReader.getFirstText("/transaction/ReturnCode");
                    tmpReturnMsg = tmpBkReader.getFirstText("/transaction/ReturnMsg");
                    tmperror = tmpBkReader.getFirstText("/transaction/error");
                }
                if (StringHelper.hasAnyChar(tmpReturnCode)) {
                    retDetail.respCode = "0";
                    retDetail.respInfo = tmpReturnMsg;
                    if (StringHelper.isNullOrEmpty(retDetail.respInfo)) {
                        retDetail.respInfo = tmperror;
                    }
                    if ("system.args".equals(tmpReturnCode)) {
                        retDetail.transState = tmpReturnCode + retDetail.respInfo;
                        retDetail.payInfoCode = retDetail.respInfo;
                    } else {
                        retDetail.transState = tmpReturnCode;
                        retDetail.payInfoCode = tmpReturnCode;
                    }
                    retDetail.reqSeqID = p_req1908.singleDetail.askNumber;//tmpBkReader.getFirstText("/Transaction/TransContent/RespData/ClientPatchID");
                    //if(StringHelper.isNullOrEmpty(retDetail.reqSeqID)){
                    //	retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    //}
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpReturnMsg;
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            retDetail.respCode = "0";
            retDetail.respInfo = tmpStrRet[1];
            retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
            retDetail.transState = PaymentState.FAIL_Payment;
            retDetail.payInfoCode = tmpStrRet[0];
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }

    /**
     * 单笔支付状态查询
     * @param p_req1944
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);

        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        CEB01Header bankHeader = new CEB01Header();
        bankHeader.TransCode = "b2e004003";
        bankHeader.batchID = getBatchID();
        bankHeader.JnlDateTime = new Date();
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader_2(xmlWriter, bankHeader);//写入通用的头部节点
        xmlWriter.writeStartElement("TransContent");
        xmlWriter.writeStartElement("ReqData");
        xmlWriter.writeElementString("ClientPatchID", bankHeader.batchID);
        xmlWriter.writeElementString("ClientBchID", p_req1944.askNumber);
        xmlWriter.writeElementString("ClientPchID", p_req1944.askNumber);
        xmlWriter.writeEndDocument();

        try {
            String[] tmpStrRet = sendToBank_2(xmlWriter.toXmlString(), bankHeader.TransCode);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpReturnCode = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnCode");
                    String tmpReturnMsg = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnMsg");
                    String tmpNowFlag = tmpBkReader.getFirstText("/Transaction/TransContent/RespData/NowFlag");
                    if (tmpNowFlag != null && "00".equals(tmpNowFlag)) {
                        String tmpClientPatchID = tmpBkReader.getFirstText("/Transaction/TransContent/RespData/ClientPatchID");
                        if (tmpClientPatchID != null && tmpClientPatchID.equals(p_req1944.askNumber)) {
                            retDetail.respCode = "0";
                            retDetail.transState = tmpBkReader.getFirstText("/Transaction/TransContent/RespData/TransferFlag");

                            retDetail.reqSeqID = p_req1944.askNumber;
                            retDetail.respInfo = tmpReturnMsg;

                            retDetail.payInfoCode = retDetail.respInfo;
                            if (StringHelper.isNullOrEmpty(retDetail.payInfoCode)) {
                                retDetail.payInfoCode = retDetail.transState;
                            }
                            retDetail.transAmt = tmpBkReader.getFirstText("/Transaction/TransContent/RespData/Amount");
                        } else {
                            retDetail.respCode = "-1";
                            retDetail.respInfo = "返回的流水号" + tmpClientPatchID + "与请求" + p_req1944.askNumber + "不符";
                        }
                    } else if (tmpReturnCode == null && tmpReturnMsg == null && tmpNowFlag == null) {
                        tmpReturnCode = tmpBkReader.getFirstText("/transaction/ReturnCode");
                        tmpReturnMsg = tmpBkReader.getFirstText("/transaction/ReturnMsg");
                        if (tmpReturnCode.equals("B2E004039")) {
                            if (canBeNotExist(p_req1944, retDetail)) {
                                retDetail.respCode = "0";
                                retDetail.respInfo = tmpReturnMsg;
                                retDetail.reqSeqID = p_req1944.askNumber;
                                retDetail.transState = tmpReturnCode;
                                retDetail.payInfoCode = tmpReturnCode;
                            }
                        } else {
                            retDetail.respCode = "-1";
                            retDetail.respInfo = tmpReturnMsg;
                        }
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpReturnMsg;
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
